package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class WebMvcInterceptor implements HandlerInterceptor {

    /**
     * 拦截器
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断用户是否登录(看session中有没有employee),如果登录就放行
        Long employeeId = (Long) request.getSession().getAttribute("employee");
        Long userId = (Long) request.getSession().getAttribute("user");
        if (employeeId != null) {
            //员工登录成功的情况下,需要将员工id存入到本地线程中ThreadLocal
            BaseContext.setCurrentId(employeeId);
            return true;
        }
        if (userId != null) {
            //员工登录成功的情况下,需要将员工id存入到本地线程中ThreadLocal
            BaseContext.setCurrentId(userId);
            return true;
        }

//表示用户没有登录,告诉前端,本次请求访问未登录,被拒接处理,响应code=0,msg=NOTLOGIN
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
        return false;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }

    /**
     * 扩建MVC消息转换器
     */
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        //1.创建一个消息转换器对象MappingJackson2HttpMessageConverter()
        MappingJackson2HttpMessageConverter mc = new MappingJackson2HttpMessageConverter();
        //TOOD最核心的操作,设置核心对象
        mc.setObjectMapper(new JacksonObjectMapper());
        //2.
    }
}
